package com.rickpan.controller;

import com.rickpan.service.DeveloperAccessService;
import com.rickpan.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 开发者认证控制器
 * 处理开发者工具的权限验证和会话管理
 * 
 * @author 开发团队协调员
 * @since 2025-07-17
 */
@RestController
@RequestMapping("/api/developer/auth")
public class DeveloperAuthController {

    private static final Logger logger = LoggerFactory.getLogger(DeveloperAuthController.class);

    @Autowired
    private DeveloperAccessService developerAccessService;

    /**
     * 开发者密码验证
     * 
     * @param request 请求体
     * @param httpRequest HTTP请求
     * @return 验证结果
     */
    @PostMapping("/verify")
    public ResponseEntity<Map<String, Object>> verifyDeveloperPassword(
            @RequestBody Map<String, String> request,
            HttpServletRequest httpRequest) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }

            // 获取输入的密码
            String password = request.get("password");
            if (password == null || password.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "密码不能为空");
                return ResponseEntity.ok(result);
            }

            // 获取客户端信息
            String ipAddress = getClientIpAddress(httpRequest);
            String userAgent = httpRequest.getHeader("User-Agent");

            // 验证密码并创建会话
            String sessionToken = developerAccessService.authenticateAndCreateSession(
                userId, password, ipAddress, userAgent);

            if (sessionToken != null) {
                result.put("success", true);
                result.put("message", "验证成功");
                result.put("sessionToken", sessionToken);
                
                logger.info("✅ 开发者认证成功: userId={}, ip={}", userId, ipAddress);
            } else {
                result.put("success", false);
                result.put("message", "密码错误或开发者工具已禁用");
                
                logger.warn("🚫 开发者认证失败: userId={}, ip={}", userId, ipAddress);
            }

        } catch (Exception e) {
            logger.error("❌ 开发者认证异常", e);
            result.put("success", false);
            result.put("message", "系统异常，请稍后重试");
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 验证开发者会话
     * 
     * @param request 请求体
     * @return 验证结果
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateDeveloperSession(
            @RequestBody Map<String, String> request) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String sessionToken = request.get("sessionToken");
            if (sessionToken == null || sessionToken.trim().isEmpty()) {
                result.put("valid", false);
                result.put("message", "会话令牌不能为空");
                return ResponseEntity.ok(result);
            }

            Long userId = developerAccessService.validateSession(sessionToken);
            
            if (userId != null) {
                result.put("valid", true);
                result.put("userId", userId);
                result.put("message", "会话有效");
            } else {
                result.put("valid", false);
                result.put("message", "会话无效或已过期");
            }

        } catch (Exception e) {
            logger.error("❌ 会话验证异常", e);
            result.put("valid", false);
            result.put("message", "系统异常");
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 销毁开发者会话
     * 
     * @param request 请求体
     * @return 操作结果
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logoutDeveloperSession(
            @RequestBody Map<String, String> request) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String sessionToken = request.get("sessionToken");
            if (sessionToken != null && !sessionToken.trim().isEmpty()) {
                developerAccessService.destroySession(sessionToken);
            }

            result.put("success", true);
            result.put("message", "已退出开发者模式");

        } catch (Exception e) {
            logger.error("❌ 退出开发者模式异常", e);
            result.put("success", false);
            result.put("message", "系统异常");
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 检查开发者工具访问权限
     * 
     * @return 权限检查结果
     */
    @GetMapping("/check-access")
    public ResponseEntity<Map<String, Object>> checkDeveloperAccess() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                result.put("hasAccess", false);
                result.put("message", "用户未登录");
                return ResponseEntity.ok(result);
            }

            // 临时调试：检查用户权限信息
            boolean isAdmin = SecurityUtils.isAdmin();
            boolean isAuthenticated = SecurityUtils.isAuthenticated();

            logger.info("🔍 开发者访问权限检查: userId={}, isAdmin={}, isAuthenticated={}",
                       userId, isAdmin, isAuthenticated);

            // 临时放宽权限检查 - 只要是认证用户就可以（仅用于调试）
            if (!isAuthenticated) {
                result.put("hasAccess", false);
                result.put("message", "用户未认证");
                return ResponseEntity.ok(result);
            }

            // TODO: 生产环境需要恢复管理员权限检查
            // if (!isAdmin) {
            //     result.put("hasAccess", false);
            //     result.put("message", "需要管理员权限");
            //     return ResponseEntity.ok(result);
            // }

            result.put("hasAccess", true);
            result.put("message", "具有访问权限");
            result.put("requiresPassword", true);

        } catch (Exception e) {
            logger.error("❌ 检查开发者访问权限异常", e);
            result.put("hasAccess", false);
            result.put("message", "系统异常");
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }
}
